using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using Framework;

public class FoodMgr : MonoSingleton<FoodMgr>
{
    private WaitForSeconds _wait = new(0.2f);

    public Image[] Maps;

    private bool isCreate;
    public bool IsCreate 
    { 
        get 
        {
            return isCreate;
        }
        set
        {
            isCreate = value;
            if (value)
            {
                InitFood();
            }
        }
    }

    private GameObject _food;

    public void Start()
    {
        _food = ResourcesMgr.Load<GameObject>("FoodItem");
        StartCoroutine(StartCreateFood());
    }

    public Image GetMap()
    {
        return Maps[Random.Range(0, Maps.Length)];
    }

    public Image GetMap(int index)
    {
        return Maps[index];
    }

    IEnumerator StartCreateFood()
    {
        while (true)
        {
            if (IsCreate)
            {
                CreateFood();
            }
            yield return _wait;
        }
    }
    
    private void CreateFood()
    {
        Image map = GetMap();
        GameObject food = Instantiate(_food, map.transform, false);
        food.transform.localPosition = CommonUtil.GetRandomPoint(map);
        if (food.TryGetComponent(out Image img))
        {
            img.color = RandomColorHSV();
        }
    }

    public void InitFood()
    {
        for (int i = 0; i < 300; i++)
        {
            CreateFood();
        }
    }

    private Color RandomColorHSV()
    {
        float h = Random.Range(0f, 1f);
        float s = Random.Range(0f, 1f);
        float v = Random.Range(0f, 1f);

        Color color = Color.HSVToRGB(h, s, v);
        return color;
    }
}
